/*
 * adc_bsp.c
 *
 *  Created on: Dec 20, 2020
 *      Author: Administrator
 */

#include	"adc_bsp.h"
#include	"stdio.h"
#include	"adc.h"



#define		ADC_SPAN		100


uint32_t	g_adc1_half_cb_cnt = 0;
uint32_t	g_adc1_cplt_cb_cnt = 0;
uint32_t	g_adc_printf_cnt = 0;


ALIGN_32BYTES (uint32_t adc1_buff[ADC1_BUF_LEN]);


void 	adc_process(void)
{

	static	uint32_t	adc_stamp;

	uint32_t	i;

	HAL_StatusTypeDef   adc_res_stat = HAL_OK;
	if(HAL_GetTick()-adc_stamp >= ADC_SPAN)
	{
		adc_stamp = HAL_GetTick();

//		printf("%d,%d,%d,%d,", adc1_buff[0],adc1_buff[1],adc1_buff[2],adc1_buff[3]);
//		printf("%d,%d,%d,%d,", adc1_buff[4],adc1_buff[5],adc1_buff[6],adc1_buff[7]);



		if(g_adc_printf_cnt < g_adc1_cplt_cb_cnt)
		{
			for(i=0;i<ADC1_BUF_LEN;i++)
			{
				uint32_t baseIdx = i;
				printf("%d\r\n", adc1_buff[baseIdx]);
			}
			g_adc_printf_cnt ++;
		}


//		printf("adc1 cb cnt: %d,%d\r\n", g_adc1_half_cb_cnt, g_adc1_cplt_cb_cnt);

//		adc_res_stat = HAL_ADC_Start_DMA(&hadc1,(uint32_t *)adc1_buff,4);
		  if (adc_res_stat != HAL_OK)
		  {
			printf("HAL_ADC_Start_DMA Error: %d\r\n", adc_res_stat);
			Error_Handler();
		  }

//		HAL_ADC_Start(&hadc1);
//		HAL_Delay(1);
//		adc_i = HAL_ADC_GetValue(&hadc1);
//		printf("%d\r\n", adc_i);
//		HAL_ADC_Stop(&hadc1);


	}
}



/* @brief  Conversion complete callback in non-blocking mode
  * @param  hadc: ADC handle
  * @retval None
  */
void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc)
{
  /* Invalidate Data Cache to get the updated content of the SRAM on the first half of the ADC converted data buffer: 32 bytes */
    if((*hadc).Instance == hadc1.Instance)
    {
//    	if(adc_printf_cnt == g_adc1_cplt_cb_cnt)
    	{
//    		SCB_InvalidateDCache_by_Addr((uint32_t *) &adc1_buff[0], ADC1_BUF_LEN);
    		g_adc1_half_cb_cnt ++;
    	}
    }
}

/**
 * @brief  Conversion DMA half-transfer callback in non-blocking mode
 * @param  hadc: ADC handle
 * @retval None
  */
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
   /* Invalidate Data Cache to get the updated content of the SRAM on the second half of the ADC converted data buffer: 32 bytes */
	if((*hadc).Instance == hadc1.Instance)
	{
//		SCB_InvalidateDCache_by_Addr((uint32_t *) &adc1_buff[ADC1_BUF_LEN/2], ADC1_BUF_LEN);
//		g_adc1_cplt_cb_cnt ++;
		g_adc1_cplt_cb_cnt = 1;
	}
}



